package com.lhy.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhy.common.constant.WareConstant;
import com.lhy.common.utils.PageUtils;
import com.lhy.common.utils.Query;
import com.lhy.gulimall.ware.dao.PurchaseDao;
import com.lhy.gulimall.ware.entity.PurchaseDetailEntity;
import com.lhy.gulimall.ware.entity.PurchaseEntity;
import com.lhy.gulimall.ware.service.PurchaseDetailService;
import com.lhy.gulimall.ware.service.PurchaseService;
import com.lhy.gulimall.ware.service.WareSkuService;
import com.lhy.gulimall.ware.vo.MergeVo;
import com.lhy.gulimall.ware.vo.PurchaseDoneVo;
import com.lhy.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),queryWrapper);

        return new PageUtils(page);

    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        // 为空 新增采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // TODO 采购单状态是0或1才可以

        Long[] items = vo.getItems();
        Long purchaseIds = purchaseId;
        List<PurchaseDetailEntity> collect = Arrays.stream(items).map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(purchaseIds);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

    /**
     *
     * @param ids 采购项id
     */
    @Override
    public void received(List<Long> ids) {

        // 确认当前采购单是新建或者是已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        // 改变采购单的状态
        this.updateBatchById(collect);

        // 改变采购项的状态
        collect.forEach(item->{
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDatailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntityCollect = purchaseDetailEntities.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntityCollect);
        });
    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        // 1、改变采购单状态
        Long id = doneVo.getId();

        // 2、改变采购项的状态
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        // 采购状态标识
        AtomicReference<Boolean> flag = new AtomicReference<>(true);
        List<PurchaseDetailEntity> collect = items.stream().map(purchaseItemDoneVo -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (purchaseItemDoneVo.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASEEROR.getCode()) {
                flag.set(false);
                detailEntity.setStatus(purchaseItemDoneVo.getStatus());
            } else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 3、将成功采购的进行入库
                PurchaseDetailEntity byId = purchaseDetailService.getById(purchaseItemDoneVo.getItemId());
                wareSkuService.addStock(byId.getSkuNum(), byId.getWareId(), byId.getSkuId());
            }
            detailEntity.setId(purchaseItemDoneVo.getItemId());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag.get() ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASEEROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

}